package com.currency.mall.ui.main;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.currency.mall.R;
import com.currency.mall.adapter.OptionalAdapter;
import com.currency.mall.di.component.DaggerOptionalComponent;
import com.currency.mall.di.modlue.OptionalModule;
import com.currency.mall.entity.SharesBean;
import com.currency.mall.ui.login.LoginActivity;
import com.currency.mall.ui.main.inquiry.InquiryDetailsActicity;
import com.currency.mall.ui.main.optional.OptionalContract;
import com.currency.mall.ui.main.optional.OptionalPresent;
import com.currency.mall.util.Util;
import com.mifengs.commonbase.base.BaseFragment;
import com.mifengs.commonbase.util.PreferenceUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;


/**
 * Created by Administrator on 2018/12/4.
 */

public class OptionalFragment extends BaseFragment<OptionalPresent> implements OptionalContract.View {

    @BindView(R.id.rv_optionalList)
    RecyclerView rvOptionalList;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    Unbinder unbinder;
    @BindView(R.id.ll_not_data)
    RelativeLayout llNotData;
    private OptionalAdapter mOptionalAdapter;
    private List<SharesBean.SharesInfo> sharesInfos = new ArrayList<>();
    private ScheduledExecutorService service;
    String strId[];

    public OptionalFragment() {

    }

    public static OptionalFragment newInstance() {
        OptionalFragment fragment = new OptionalFragment();
        return fragment;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View mView = inflater.inflate(R.layout.fragment_optional, container, false);
        unbinder = ButterKnife.bind(this, mView);
        init();
        return mView;
    }

    @Override
    public void initInjector() {
        DaggerOptionalComponent.builder()
                .optionalModule(new OptionalModule(this))
                .build()
                .inject(this);
    }

    public void reloadOptional() {
        init();
    }

    private void init() {
        rvOptionalList.setLayoutManager(new LinearLayoutManager(getContext()));
        rvOptionalList.setNestedScrollingEnabled(false);
        mOptionalAdapter = new OptionalAdapter(null, getContext());
//        View headerView = getLayoutInflater().inflate(R.layout.header_optional, null);
//        headerView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//        mOptionalAdapter.addHeaderView(headerView);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setEnableRefresh(true);
        rvOptionalList.setAdapter(mOptionalAdapter);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (refreshLayout != null) {
                    mPresenter.getCollectSharesId(false);
                }
            }
        });
        mOptionalAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                SharesBean.SharesInfo sharesInfo = sharesInfos.get(position);
                if (view.getId() == R.id.ll_collect) {
                    if (Util.useList(strId, sharesInfo.getId())) {
                        mPresenter.cancelCollectShares(sharesInfo.getId());
                    } else {
                        mPresenter.collectSharesInfo(sharesInfo.getId());
                    }
                } else {
                    Intent intent = new Intent(getContext(), InquiryDetailsActicity.class);
                    startActivity(intent);
                }
            }
        });

        mOptionalAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                SharesBean.SharesInfo sharesInfo = sharesInfos.get(position);
                Intent intent = new Intent(getContext(), InquiryDetailsActicity.class);
                intent.putExtra("sharesInfo", sharesInfo);
                startActivity(intent);
            }
        });
        mPresenter.getCollectSharesId(false);
        service = Executors.newScheduledThreadPool(1);
        service.scheduleAtFixedRate(new VisibleScheduledExecutor(), 10, 5, TimeUnit.SECONDS);
    }

    @Override
    public void setSharesData(List<SharesBean.SharesInfo> sharesInfoList, boolean isLoadOver) {
        if(sharesInfoList != null){
            llNotData.setVisibility(View.GONE);
        }else{
            llNotData.setVisibility(View.VISIBLE);
        }
        sharesInfos = sharesInfoList;
        mOptionalAdapter.setCollectShareId(strId);
        mOptionalAdapter.setNewData(sharesInfos);
    }

    public void finishRefresh() {
        if (refreshLayout != null)
            refreshLayout.finishRefresh();
    }

    @Override
    public void refresh() {
        mPresenter.getCollectSharesId(false);
    }

    @Override
    public void collectSharesId(String[] str) {
        strId = str;
        mPresenter.getCollectShares();
    }

    @Override
    public void toLogin() {
        startActivity(new Intent(getContext(), LoginActivity.class));
    }

    Handler mHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (PreferenceUtils.getLoginStatus())
                        mPresenter.getCollectSharesId(true);
                    break;
            }
        }
    };

    @OnClick(R.id.ll_search)
    public void onViewClicked() {
        startActivity(new Intent(getContext(), SearchActivity.class));
    }

    class VisibleScheduledExecutor implements Runnable {

        @Override
        public void run() {
//            mSuspensionLayout.setVisibility(View.VISIBLE);
            Message msg = new Message();
            msg.what = 1;
            mHandle.sendMessage(msg);
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        shutDownService();
    }


    private void shutDownService() {
        if (service != null) {
            try {
                service.shutdown();
                if (!service.awaitTermination(1, TimeUnit.MILLISECONDS)) {
                    service.shutdownNow();
                }
            } catch (Exception exception) {
                service.shutdownNow();
            }
        }


    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            shutDownService();
        } else {
            service = Executors.newScheduledThreadPool(1);
            service.scheduleAtFixedRate(new VisibleScheduledExecutor(), 10, 5, TimeUnit.SECONDS);
        }
    }


}
